<template>
  <div>
    <ElButton @click="onClose()">取消</ElButton>
    <ElButton type="primary" @click="onOk()">确 定</ElButton>

    <ElButton v-if="visibleApproveBtn" type="primary" @click="doApprove()">同意</ElButton>
    <ElButton v-if="userTaskConfigObj.disabledBtnJson.turnBtn" type="primary" plain @click="doAssignTask()">
      转办
    </ElButton>
    <ElButton v-if="userTaskConfigObj.disabledBtnJson.delegateBtn" type="primary" plain @click="doDelegateTask()">
      委派
    </ElButton>
    <ElButton v-if="userTaskConfigObj.disabledBtnJson.backBtn" type="primary" plain @click="doReturnTask()">
      回退
    </ElButton>
    <ElButton
      v-if="userTaskConfigObj.disabledBtnJson.beforeSignBtn"
      type="primary"
      plain
      @click="doBeforeAddSignTask()">
      前加签
    </ElButton>
    <ElButton v-if="userTaskConfigObj.disabledBtnJson.afterSignBtn" type="primary" plain @click="doAfterAddSignTask()">
      后加签
    </ElButton>
    <ElButton v-if="userTaskConfigObj.disabledBtnJson.reverseSign" type="primary" plain @click="doUnClaimTask()">
      反签收
    </ElButton>
    <ElButton v-if="visibleSendBtn" type="primary" plain @click="doSendUserTask()">发送</ElButton>
    <ElButton v-if="userTaskConfigObj.disabledBtnJson.stopBtn" type="warning" plain @click="doStopProcess()">
      终止
    </ElButton>
    <!-- 用户信息 -->
    <FlowableHandleUserTable
      :visible.sync="visibleUser"
      :selection="selection"
      :multiple="multiple"
      @getUserList="getUserList" />
    <!-- 回退 -->
    <ReturnTaskUserModel
      ref="returnTaskUserModel"
      :visible.sync="visibleReturn"
      :task-id="taskObj.taskId"
      :process-instance-id="taskObj.processInstanceId"
      @getHandleRecordActivityInfo="getHandleRecordActivityInfo" />
    <!-- 加签 -->
    <AddSignatureModel :visible.sync="visibleSignature" @getAddSignature="getAddSignature" />

    <!-- 自由发送 -->
    <SendUserTaskModel
      ref="sendUserTaskModel"
      :visible.sync="visibleSendUserTask"
      :task-id="taskId"
      @getSendUserTask="getSendUserTask" />
    <!-- 办理意见 -->
    <ApprovalMessageModel ref="approvalMessageModel" :visible.sync="visibleMessageModel" @getMessage="getMessage" />
  </div>
</template>

<script>
  import {
    complete,
    stopProcess,
    assignTask,
    delegateTask,
    taskReturn,
    beforeAddSignTask,
    afterAddSignTask,
    sendUserTask,
    nextFlowNodeList,
    findReturnTaskList,
    unClaimTask,
    getAppingTasksModel,
    getTaskVoByProcessInstanceId
  } from '@/api/admin/workitem'

  import { getUserTaskConfigObj } from '@/api/admin/actusertaskconfig'
  import ReturnTaskUserModel from '@/module/process/components/ReturnTaskUserModel'
  import AddSignatureModel from '@/module/process/components/AddSignatureModel'
  import SendUserTaskModel from '@/module/process/components/SendUserTaskModel'
  import ApprovalMessageModel from '@/module/process/components/ApprovalMessageModel'
  import FlowableHandleUserTable from '@/module/process/components/FlowableHandleUserTable'
  import { mapState } from 'vuex'

  export default {
    name: 'FlowableHandleApprovalModel',
    components: {
      FlowableHandleUserTable,
      ReturnTaskUserModel,
      AddSignatureModel,
      SendUserTaskModel,
      ApprovalMessageModel
    },
    props: {
      propParams: {
        type: Object
      }
    },
    data() {
      return {
        visibleUser: false,
        userObj: {},
        userSelectType: -1,
        addSignatureType: -1,
        visibleReturn: false,
        visibleSignature: false,
        selection: true,
        multiple: false,
        visibleSendUserTask: false,
        flowNodeList: [],
        visibleSendBtn: false,
        visibleApproveBtn: false,
        visibleMessageModel: false,
        returnTaskList: [],
        taskId: '',
        userTaskConfigObj: {
          disabledBtnJson: {
            turnBtn: false,
            afterSignBtn: false,
            beforeSignBtn: false,
            delegateBtn: false,
            reverseSign: false,
            stopBtn: false
          }
        },
        taskObj: {}
      }
    },
    computed: {
      ...mapState('user', ['sysUser'])
    },
    mounted() {
      this.$emit('loadEnd')
    },

    methods: {
      initParams(propParams) {
        if (propParams.taskId === '-1') {
          getTaskVoByProcessInstanceId(propParams.processInstanceId).then(result => {
            this.taskObj = result.data.data
            return this.init(this.taskObj, this.taskObj.hasCurUserHandle)
          })
        } else {
          getAppingTasksModel(propParams.taskId).then(response => {
            this.taskObj = response.data.data
            return this.init(this.taskObj, true)
          })
        }
      },
      init(paramsObj, hasCurUserHandle) {
        if (!hasCurUserHandle) {
          return
        }
        // 获取当前任务配置信息。
        getUserTaskConfigObj(paramsObj.processInstanceId, paramsObj.taskId, paramsObj.taskDefKey).then(response => {
          this.userTaskConfigObj = response.data.data
          this.handleHideFormField()
        })
        // 查询下个环节
        nextFlowNodeList({ taskId: paramsObj.taskId }).then(response => {
          this.flowNodeList = response.data.data
          if (response.data.success) {
            this.visibleSendBtn = true
          } else {
            this.visibleApproveBtn = true
          }
        })
        // 查询回退环节
        const params = { taskId: paramsObj.taskId, processInstanceId: paramsObj.processInstanceId }
        findReturnTaskList(params).then(response => {
          this.returnTaskList = response.data.data
          if (!this.returnTaskList.length > 0) {
            this.userTaskConfigObj.disabledBtnJson.backBtn = false
          }
        })
      },
      doApprove() {
        this.visibleMessageModel = true
        this.$refs.approvalMessageModel.showModel('approve', '请输入审批意见！')
      },
      doStopProcess() {
        this.visibleMessageModel = true
        this.$refs.approvalMessageModel.showModel('stopBtn', '请输入终止意见！')
      },
      // 转办
      doAssignTask() {
        this.userSelectType = 0
        this.visibleUser = true
        this.selection = true
        this.multiple = false
      },
      // 委派
      doDelegateTask() {
        this.userSelectType = 1
        this.visibleUser = true
        this.selection = true
        this.multiple = false
      },
      doReturnTask() {
        this.visibleReturn = true
        this.$refs.returnTaskUserModel.setReturnTaskList(this.returnTaskList)
      },
      doBeforeAddSignTask() {
        this.addSignatureType = 0
        this.visibleSignature = true
        this.selection = true
        this.multiple = true
      },
      doAfterAddSignTask() {
        this.addSignatureType = 1
        this.visibleSignature = true
        this.selection = true
        this.multiple = true
      },
      doSendUserTask() {
        this.$refs.sendUserTaskModel.setFlowNodeList(this.flowNodeList, this.propParams)
        this.visibleSendUserTask = true
      },
      doUnClaimTask() {
        this.visibleMessageModel = true
        this.$refs.approvalMessageModel.showModel('unclaimTask', '请输入反签收意见！')
      },
      getUserList(userList, message) {
        this.userObj = userList
        const data = {
          taskId: this.taskObj.taskId,
          assignee: this.userObj.username,
          message,
          processInstanceId: this.taskObj.processInstanceId,
          activityId: this.taskObj.taskDefKey,
          activityName: this.taskObj.name
        }
        // 转办
        if (this.userSelectType === 0) {
          this.$confirm(`是否将该任务转办至${this.userObj.realName}办理？`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            data.processStatusEnum = 'ZB'
            assignTask(data).then(response => {
              if (response.data.success) {
                this.$message.success('转办成功。')
                this.onClose()
              }
            })
          })
        }
        // 委派
        if (this.userSelectType === 1) {
          if (this.userObj.username === this.sysUser.username) {
            this.$message.warning('不能委派给自己办理！')
            return
          }
          this.$confirm(`是否将该任务委派至${this.userObj.realName}办理？`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            data.processStatusEnum = 'WP'
            delegateTask(data).then(response => {
              if (response.data.success) {
                this.$message.success('委派成功。')
                this.onClose()
              }
            })
          })
        }
      },
      getHandleRecordActivityInfo(obj) {
        const data = {
          message: obj.comment,
          distFlowElementId: obj.activityId,
          activityId: this.taskObj.taskDefKey,
          activityName: this.taskObj.name,
          taskId: this.taskObj.taskId,
          processInstanceId: this.taskObj.processInstanceId,
          processStatusEnum: 'TH',
          variables: {
            approval: obj.userCode,
            userList: obj.userCode.split(','),
            days: 4
          }
        }
        this.$confirm('是否退回该任务？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          taskReturn(data).then(response => {
            if (response.data.success) {
              this.$message.success('退回成功！')
              this.onClose()
            }
          })
        })
      },
      getAddSignature(signature) {
        const data = {
          signPersoneds: signature.signPersoneds,
          message: signature.message,
          activityId: this.taskObj.taskDefKey,
          activityName: this.taskObj.name,
          taskId: this.taskObj.taskId,
          processInstanceId: this.taskObj.processInstanceId,
          processStatusEnum: 'SPZ'
        }
        if (this.addSignatureType === 0) {
          // 前加签
          beforeAddSignTask(data).then(response => {
            if (response.data.success) {
              this.$message.success(response.data.msg)
              this.onClose()
            }
          })
        } else {
          // 后加签
          afterAddSignTask(data).then(response => {
            if (response.data.success) {
              this.$message.success(response.data.msg)
              this.onClose()
            }
          })
        }
      },
      getSendUserTask(obj) {
        const params = {
          taskId: this.taskObj.taskId,
          processInstanceId: this.taskObj.processInstanceId,
          message: obj.message,
          commentTypeEnum: 'SP',
          processStatusEnum: 'SPZ',
          activityId: this.taskObj.taskDefKey,
          activityName: this.taskObj.name,
          variables: {
            approval: obj.approval.join(','),
            userList: obj.approval,
            days: 4
          }
        }
        if (obj.complete) {
          complete(params).then(response => {
            if (response.data.success) {
              this.$message.warning('审批成功。')
              this.onClose()
            }
          })
        } else {
          // 自由审批
          params.distFlowElementId = obj.activityId
          sendUserTask(params).then(response => {
            if (response.data.success) {
              this.$message.warning(response.data.msg)
              this.onClose()
            }
          })
        }
      },
      getMessage(message, type) {
        if (type === 'stopBtn') {
          this.handleStop(message)
        }
        if (type === 'approve') {
          this.handleApprove(message)
        }
        if (type === 'unclaimTask') {
          this.handelUnClaimTask(message)
        }
      },
      handleHideFormField() {
        const hideFormField = this.propParams.hideFormField
        const visibleHideFormField = this.propParams.visibleHideFormField
        // 处理表单的显示和隐藏。
        const hideFormJson = this.userTaskConfigObj.hideFormJson
        if (!this.$isBlank(hideFormJson) && !this.$isBlank(hideFormField) && !this.$isBlank(visibleHideFormField)) {
          hideFormField.forEach(field => {
            if (!this.$isBlank(hideFormJson[field])) {
              visibleHideFormField[field] = hideFormJson[field]
            }
          })
          // 回调表单控制。
          this.$emit('callBackhideFormField', visibleHideFormField)
        }
      },
      handelUnClaimTask(message) {
        const params = {
          taskId: this.taskObj.taskId,
          processInstanceId: this.taskObj.processInstanceId,
          message,
          commentTypeEnum: 'FQS',
          processStatusEnum: 'DQS',
          activityId: this.taskObj.taskDefKey,
          activityName: this.taskObj.name
        }
        this.$confirm('是否反签收该任务？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          unClaimTask(params).then(response => {
            if (response.data.success) {
              this.$message.warning(response.data.msg)
              this.onClose()
            }
          })
        })
      },
      // 审批
      handleApprove(message) {
        const params = {
          taskId: this.taskObj.taskId,
          processInstanceId: this.taskObj.processInstanceId,
          message,
          commentTypeEnum: 'SP',
          processStatusEnum: 'SPZ'
        }
        complete(params).then(response => {
          if (response.data.success) {
            this.$message.warning('审批成功。')
            this.onClose()
          }
        })
      },
      // 终止
      handleStop(message) {
        const params = {
          taskId: this.taskObj.taskId,
          processInstanceId: this.taskObj.processInstanceId,
          message,
          commentTypeEnum: 'LCZZ',
          processStatusEnum: 'ZZ'
        }
        this.$confirm('是否终止该条流程信息？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            stopProcess(params).then(response => {
              if (response.data.success) {
                this.$message.warning('终止成功。')
                this.onClose()
              }
            })
          })
          .then(() => {})
      },
      onClose() {
        this.$emit('closeModel')
      },
      onOk() {
        this.$emit('dataFormSubmit')
      }
    }
  }
</script>
